package com.jy.project.filter;


import com.jy.project.domain.User;
import com.jy.project.mapper.UserMapper;
import com.jy.project.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.util.*;

@Slf4j
@Component
public class ParamFilter implements Filter {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void doFilter(ServletRequest request, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("进入过滤器");
        String token = ((HttpServletRequest) request).getHeader("token");
        Long  userId=-1L;
        if (StringUtils.isNotEmpty(token)) {
            User u = JwtUtils.verifyToken(token);
            Long id = u.getId();
            User user = userMapper.selectByPrimaryKey(id);
            if (user!=null){
                userId=user.getId();
            }
        }
        final  Long finalUserId = userId;

        String requestURI = ((HttpServletRequest) request).getRequestURI();

        HttpServletRequestWrapper httpRequestWrapper=new HttpServletRequestWrapper((HttpServletRequest) request){
            @Override
            public Enumeration<String> getParameterNames() {
                Set<String> sets=new HashSet<>();
                Enumeration<String> parameterNames = super.getParameterNames();
                while (parameterNames.hasMoreElements()){
                    sets.add(parameterNames.nextElement());
                }
                sets.add("userId");
                sets.add("operatorUserId");
                sets.add("createUserId");
                Enumeration<String> enumeration = Collections.enumeration(sets);
                return enumeration;
            }
            @Override
            public String[] getParameterValues(String name) {
                if ("userId".equals(name)) {
                    return new String[]{finalUserId.toString()};
                }
                if ("operatorUserId".equals(name)) {
                    return new String[]{finalUserId.toString()};
                }
                if ("createUserId".equals(name)) {
                    return new String[]{finalUserId.toString()};
                }
                return super.getParameterValues(name);
            }
        };
        filterChain.doFilter(httpRequestWrapper,servletResponse);
    }
}
